<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brandIndex\BrandMsg;
use Biz\model\GoodsTestActivity\FineGoodsContentModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\wiki\Wiki;
use Biz\service\BrandIndex;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Biz\tools\helper\Common;
use Doraemon\cache\UserCounter;
use Doraemon\model\Es\MainContent;
use Doraemon\service\User as mUser;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;


class ReportListController extends Controller
{
    public const PAGE_SIZE = 20;
    //选中 1  未选择 2
    public const SELECED_STATUS = 1;
    public const UNSELECED_STATUS = 2;
    public const STATUS_ARR = [
        self::SELECED_STATUS => '已选中',
        self::UNSELECED_STATUS => '未选择',
    ];


    public function index(Request $request, Content $content, $fine_goods_id)
    {
        Admin::script($this->toShipScript());
        Admin::script($this->auditScript());
        try {
            // 填充页面body部分，这里可以填入任何可被渲染的对象
            $params = $request->all();
            (int)$wiki_type = $params['wiki_type'] ?: 3;

            //获取基础信息
            $base_info = FineGoodsModel::first(['id' => $fine_goods_id], ['basic_id', 'brand_id','type']);
            if (!$base_info) {
                throw new Exception('该活动不存在！');
            }
            $basic_id = $base_info['basic_id'];
            $brand_id = $base_info['brand_id'];
            $where['fine_goods_id'] = $fine_goods_id;
            $where['join_status'] = FineGoodsJoinModel::JOIN_STATUS_PREFER;
            $join_info = FineGoodsService::getJoinInfoById($where, ['fine_goods_id', 'uid']);
            if (!$join_info) {
                throw new Exception('该活动不存在参与名单！');
            }
            $uids = array_column($join_info, 'uid');
//            $uids = [13822, 401832];
            $user_info = mUser::getBatchBasicUserInfo($uids);
            if (!$user_info) {
                throw new Exception('无用户参与！');
            }
            $c_field = ['obj_id', 'points'];
            //获取选中的内容
            $join_content = FineGoodsService::getSelectedContent($fine_goods_id, $c_field);
            $content->row(
                "
                <li style='font-size: 18px;color: #1E9FFF'> 已确定内容：" . count($join_content) . "</li>
                <li style='font-size: 18px;color: #00a7d0'> 本期测评数量：" . count($join_info) . "</li>
                "
            );
            $join_content = array_column($join_content, null, 'obj_id') ?? [];
            $es_info_json = MainContent::getNotesForFineGoodsTest($uids);
            if (!$es_info_json) {
                throw new Exception('es中内容不存在！');
            }
            $es_info = $es_info_json['rows'];
            $es_ids = array_column($es_info, 'id');
//            $end_time = FineGoodsModel::first(['id' => $fine_goods_id], 'schedule_end_time');
//            $es_ids = ['0000376000000any', '000000s050008m20'];
            \Doraemon\tools\Log::debug('好物轻测-es拉取数据', $es_info);
            $wiki_id = Wiki::getInfoByBasicId($basic_id,'id');
            if (!$wiki_id) {
                throw new Exception('商品不存在！');
            }
            $obj_info = FineGoodsService::getObjInfo($es_ids, $wiki_type, (int)$wiki_id);
            foreach ($obj_info as &$info) {
                $info['points'] = $join_content[$info['obj_id']]['points'] ?? 0;
                $info['status'] = $join_content[$info['obj_id']]['points'] ? self::SELECED_STATUS : self::UNSELECED_STATUS;
                $info['content_id'] = $join_content[$info['obj_id']]['id'] ?? '';
                $info['fine_goods_id'] = $fine_goods_id;
            }

            if (!$obj_info) {
                throw new Exception('该活动不存在测评报告！');
            }
            $report_list = Common::keyBy($obj_info, 'uid') ?? [];

            if (!$report_list) {
                throw new Exception('无数据！');
            }
            $counter = UserCounter::getMultiByUids($uids);
            foreach ($user_info as &$item) {
                $item['report_list'] = isset($report_list[$item['uid']]) ? $this->_getNoteExpand($report_list[$item['uid']]) : '';
                $item['id'] = $item['uid'];
                $item['fans'] = $counter[$item['uid']]['fans'] ?? 0;
            }
            //数据已查完  组装列表
            $count = count($user_info);
            $gridModel = new GridDataModel($user_info, $count);
            $grid = Admin::grid($gridModel,
                function (Grid $grid) {
                    $grid->disablePagination();
                    $grid->disableCreateButton();
                    $grid->filter(function ($filter) {
                        // 去掉默认的id过滤器
                        $filter->disableIdFilter();
                        // 在这里添加字段过滤器
                        $filter->column(1 / 2, function ($filter) {
                            $filter->equal('wiki_type', '查看类型')->select([
                                1 => '有wiki',
                                2 => '无wiki',
                            ]);
                        });
                        $filter->expand();//默认展开
                    });
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->column('id', '用户ID')->expand(function () {
                        return $this->report_list;
                    });
                    $grid->column('nick', '用户名称');
                    $grid->column('fans', '粉丝数量');
                    $grid->disableActions();
                }
            );


            $tab = new Tab();
            $tab->addLink("活动详情页 ", url("/admin/goodsTest/detail/$fine_goods_id"), false);
            $tab->addLink('获选名单', url("/admin/goodsTest/joinSelected/index/$fine_goods_id"), false);
            $tab->add('测评报告管理', $grid->render(), true);
            $tab->addLink('测评报告', url("/admin/goodsTest/detail/report/$fine_goods_id"), false);
            $content->row($tab);


            return $content
                ->header(FineGoodsModel::TYPE_MAP[$base_info['type']]." | 测评报告管理")
                ->description(' ')
                ->breadcrumb(['text' => '审核列表', 'url' => '/goodsTest/index'], ['text' => '测评报告管理']);

        } catch (Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }
    }

    /**
     * 打分
     * @return string
     */
    private function toShipScript(): string
    {
        return <<<SCRIPT
        $('.to-check').unbind('click').click(function(){
            var id=$(this).data('id');
            var uid=$(this).data('uid');
            var state=$(this).data('state');
            var fine_goods_id=$(this).data('fid');
            layer.open({
                type: 2,
                title: '',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['600px', '600px'],
                content: '/admin/goodsTest/reportList/index/'+id+'/'+fine_goods_id+'/'+uid+'/editAudit',
            });
        });
SCRIPT;
    }

    /**
     * 取消选中
     * @return string
     */
    private function auditScript()
    {
        return <<<SCRIPT
        $('.un_pass-data').unbind('click').click(function(){
        
            var id= $(this).data('id');
            var fine_goods_id=$(this).data('fid');
            let url = '/admin/goodsTest/reportList/index/cancelSelected';
            let params = {id:id,fine_goods_id:fine_goods_id};
            swal({
                    title: "确认取消吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    /**
     * form子页面
     * @param $list
     * @return string
     */
    private function _getNoteExpand($list)
    {
        $row = new Row();
        $count = count($list);
        $gridModel = new GridDataModel($list, $count);
        $grid = new Grid($gridModel);
        $grid->disablePagination();
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableRowSelector();
        $grid->disableColumnSelector();
        $grid->disableTools();
        $grid->disableExport();
        $grid->column('obj_id', '内容ID')->modal('关联商品', function () {
            $wiki_info = $this->wiki_list;
            $data = [];
            if ($wiki_info) {
                foreach ($wiki_info as $item) {
                    $data[] = [
                        'id' => $item['id'],
                        'basic_id' => $item['basic_id'],
                        'title' => $item['title'],
                        'cover_img' => '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'845px\'],content: \'' . $item['cover_img'] . '\'});">
                                <img width="100px" height="100px" src="' . $item['cover_img'] . '">
                            </a>',
                    ];
                }
            }

            return new Table(['商品id', 'WIKI ID', '标题', '图片'], $data);
        })->copyable();

        $grid->column('cover_image', '首图')->display(function ($cover_img) {
            return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'845px\'],content: \'' . $cover_img . '\'});">
                                <img width="100px" height="100px" src="' . $cover_img . '">
                            </a>';
        });

        $grid->column('title', '标题')->display(function () {

            $objType = IdParse::getType($this->obj_id);
            $url = '';
            if ($objType == BlockType::TYPE_PHOTO) {
                $url = Hhzurl::h5PhotoShow($this->obj_id);
            }
            if ($objType == BlockType::TYPE_BLANK) {
                $url = Hhzurl::h5BlankShow($this->obj_id);
            }
            $html = '<ul class="list-unstyled">';
            $html .= '<li>' . $this->title . '</li>';
            $html .= '<li><a class="fa fa-chain" href="javascript:layer.open({
                                type: 2,
                                title: \'内容详情\',
                                maxmin: true,
                                shade: 0.8,
                                shadeClose: true,
                                area: [\'500px\', \'700px\'],
                                content: \'' . $url . '\'
                            });">预览</a></li>';
            $html .= '</ul>';

            return $html;
        })->width(120);
        $grid->column('add_time', '添加时间');
        $grid->column('points', '分数');
        $grid->column('link')->newQrcode();
        $grid->column('status', '状态')->using(
            self::STATUS_ARR
            , '未知')->label([
            1 => 'success',
            2 => 'danger',
        ]);
        $selected = self::SELECED_STATUS;
        $un_selected = self::UNSELECED_STATUS;
        $grid->actions(function (Grid\Displayers\Actions $actions) use ($selected, $un_selected) {
            $actions->disableEdit();
            $actions->disableDelete();
            if ($actions->row->status === $selected) {
                $html = '<a class="fa un_pass-data" data-state="' . $un_selected . '" data-fid="' . $actions->row->fine_goods_id . '" data-id="' . $actions->row->obj_id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>';
            } else {
                $html = ' <a class="fa edit-pass-data to-check" data-state="' . $selected . '"  data-fid="' . $actions->row->fine_goods_id . '"  data-uid="' . $actions->row->uid . '" data-id="' . $actions->row->obj_id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-ok" aria-hidden="true"></span></a>';
            }
            $actions->prepend($html);
        });
        $row->column(12, $grid);

        return $row->render();
    }

    /**
     * 打分页面
     * @param Request $request
     * @param WorkContent $content
     * @param $id
     * @param $fine_goods_id
     * @param $uid
     * @return Content|RedirectResponse
     */
    public function editAudit(Request $request, WorkContent $content, $id, $fine_goods_id, $uid)
    {
        $params = $request->all();
        $code = $params['code'] ?? 0;
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
            SCRIPT;
            Admin::script($script);
        }
        if (!$id || !$fine_goods_id) {
            $error = new MessageBag([
                'title' => '参数错误',
            ]);

            return back()->with(compact('error'));
        }

        $basic_id = FineGoodsModel::first(['id' => $fine_goods_id], 'basic_id');
        $info['basic_id'] = $basic_id;
        $info['id'] = $id;
        $info['fine_goods_id'] = $fine_goods_id;
        $info['uid'] = $uid;

        $form = new Form($info);
        $form->hidden('basic_id', $basic_id);
        $form->hidden('id', $id);
        $form->hidden('fine_goods_id', $fine_goods_id);
        $form->hidden('uid', $uid);


        $form->radio('points', '分数')->options([1 => '1分', 2 => '2分', 3 => '3分', 4 => '4分', 5 => '5分'])->default(3);
        $form->action('/admin/goodsTest/reportList/index/save');

        return $content
            ->body($form);

    }

    /**
     * 保存打分
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        $params = $request->all();
        try {
            $id = $params['id'];
            $fine_goods_id = $params['fine_goods_id'];
            $uid = $params['uid'];
            $act_info = FineGoodsModel::first(['id' => $fine_goods_id],
                ['brand_id', 'report_num', 'basic_title', 'activity_title','type']);
            $report_num = $act_info['report_num'] ?? 0;
            $is_delete = FineGoodsContentModel::IS_DELETE_FALSE;
            $where['obj_id'] = $id;
            $where['fine_goods_id'] = $params['fine_goods_id'];
            $isset = FineGoodsContentModel::first($where);
            $data['obj_id'] = $params['id'];
            $data['fine_goods_id'] = $params['fine_goods_id'];
            $data['basic_id'] = $params['basic_id'];
            $data['points'] = $params['points'];
            $data['operate_id'] = Admin::user()->id;
            $data['uid'] = $params['uid'];
            if ($isset) {
                $up_data['is_delete'] = $is_delete;
                $up_data['points'] = $params['points'];
                FineGoodsContentModel::update($up_data, $where);
            } else {
                FineGoodsContentModel::insert($data);
            }
            ++$report_num;
            FineGoodsModel::update(['report_num' => $report_num], ['id' => $fine_goods_id]);
            if($act_info['type'] < FineGoodsModel::TYPE_EVALUATION) { //只有轻测和开箱类型活动 需要通知品牌后台
                $activityName = FineGoodsModel::TYPE_MAP_BACKUPS[$act_info['type']];
                $msg = "你所提报的 %s {$activityName}活动，测评内容已选出。";
                $msg = sprintf($msg, $act_info['basic_title']);
                BrandIndex::writeMsg($act_info['brand_id'], BrandMsg::MSG_TYPE_PASS,
                    BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
            }


        } catch (Exception $e) {
            $error = new MessageBag(['title' => $e->getMessage()]);

            return redirect("/admin/goodsTest/reportList/index/$id/$fine_goods_id/$uid/editAudit")->with(compact('error'));
        }
        $success = new MessageBag(['title' => '操作成功']);

        return redirect("/admin/goodsTest/reportList/index/$id/$fine_goods_id/$uid/editAudit?code=1")->with(compact('success'));


    }

    /**
     * 取消选中
     * @param Request $request
     * @return JsonResponse
     */
    public function cancelSelected(Request $request): JsonResponse
    {
        try {
            $params = $request->all();
            $id = $params['id'];
            $fine_goods_id = $params['fine_goods_id'];
            $report_num = FineGoodsModel::first(['id' => $fine_goods_id], 'report_num');
            $is_delete = FineGoodsContentModel::IS_DELETE_TRUE;
            $where['obj_id'] = $id;
            $where['fine_goods_id'] = $fine_goods_id;
            $isset = FineGoodsContentModel::first($where, 'id');
            if (!$isset) {
                throw new Exception("该记录不存在！");
            }
            $up_data['is_delete'] = $is_delete;
            $up_data['points'] = 0;
            FineGoodsContentModel::update($up_data, $where);
            --$report_num;
            FineGoodsModel::update(['report_num' => $report_num], ['id' => $fine_goods_id]);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);
    }



//    private function _formatList($note_lists, $counter)
//    {
//        $list = [];
//        foreach ($note_lists as $obj_id => $note_list) {
//            if ((int)$note_list['type'] === BlockType::TYPE_PHOTO) {
//                $user_info = $note_list['photo']['user_info'];
//                $report_info['cover_img'] = $note_list['photo']['photo_info']['image_list'][0] ?? '';
//                $report_info['title'] = $note_list['photo']['photo_info']['title'];
//                $report_info['remark'] = $note_list['photo']['photo_info']['remark'];
//                $report_info['addtime'] = date("Y-m-d H:i:s", $note_list['photo']['photo_info']['addtime']);
////                    $report_info['has_goods'] = $note_list['photo']['photo_info']['has_goods'];
//                $report_info['id'] = $note_list['photo']['photo_info']['id'];
////                $user_info = $note_list['photo']['user_info'];
//            }
//            if ((int)$note_list['type'] === BlockType::TYPE_BLANK) {
//
//                $user_info = $note_list['blank']['user_info'];
//                $report_info['cover_img'] = $note_list['blank']['blank_info']['cover_pic_url'] ?? '';
//                $report_info['title'] = $note_list['blank']['blank_info']['title'];
//                $report_info['remark'] = $note_list['blank']['blank_info']['remark'];
//                $report_info['addtime'] = date("Y-m-d H:i:s", $note_list['blank']['blank_info']['addtime']);
//                $report_info['id'] = $note_list['blank']['blank_info']['id'];
////                    $report_info['has_goods'] = $note_list['blank']['blank_info']['has_goods'];
//            }
//            $uid = $user_info['uid'];
//            $list[$uid]['nick'] = $user_info['nick'];
//            $list[$uid]['uid'] = $user_info['uid'];
//            $list[$uid]['fans'] = $counter[$uid]['fans'];
//            $list[$uid]['avatar'] = $user_info['avatar'];
//            $list[$uid]['cover_img'] = $report_info['cover_img'];
//            $list[$uid]['report_info'][] = $report_info;
//
//        }
//        return $list;
//    }


}